<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="40px">
      <el-form-item>
        <el-input v-model="queryParams.projectname" :placeholder="$t('common.enterProjectName')" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('common.search') }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('common.reset') }}</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['iot:project:add']">{{ $t('common.add') }}</el-button>
      </el-col>
      <el-col :span="1.5">
<el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['iot:project:edit']">{{ $t('common.edit') }}</el-button>
      </el-col>
      <el-col :span="1.5">
<el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['iot:project:remove']">{{ $t('common.delete') }}</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"/>
    </el-row>
    <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column :label="$t('common.number')" align="center" prop="id" />
      <el-table-column :label="$t('iot.customerName')" align="center" prop="sysUser.nickName" />
      <el-table-column :label="$t('iot.projectName')" align="center" prop="projectname" />
      <el-table-column :label="$t('iot.provinceCity')" align="center" prop="city" />
      <el-table-column :label="$t('iot.cityCode')" align="center" prop="citycode" />
      <el-table-column :label="$t('iot.projectAddress')" align="center" prop="projectAddress" />
      <el-table-column :label="$t('iot.approvalTime')" align="center">
        <template slot-scope="scope">{{formatDate(scope.row.approvaltime)}}</template>
      </el-table-column>
      <el-table-column :label="$t('common.updateTime')" align="center">
        <template slot-scope="scope">{{scope.row.updatetimeFormatted||$t('iot.notUpdated')}}</template>
      </el-table-column>
      <el-table-column :label="$t('common.remark')" align="center" prop="remark" />
      <el-table-column :label="$t('common.status')" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status==='normal'" type="success">{{ $t('common.normal') }}</el-tag>
          <el-tag v-else-if="scope.row.status==='hidden'" type="danger">{{ $t('common.hidden') }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.operation')" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['iot:project:edit']">{{ $t('common.edit') }}</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['iot:project:remove']">{{ $t('common.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item :label="$t('iot.customerName')" prop="nickName">
          <el-select v-model="form.userId" :placeholder="$t('iot.selectCustomer')" filterable @change="handleSelectChange">
            <el-option v-for="item in options" :key="item.userId" :label="item.nickName" :value="item.userId"/>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('iot.projectName')" prop="projectname">
          <el-input v-model="form.projectname" :placeholder="$t('common.enterProjectName')" />
        </el-form-item>
        <el-form-item :label="$t('iot.areaSelect')" prop="area">
          <el-cascader ref="cascader" :options="areaOptions" v-model="selectedArea" :props="cascaderProps" @change="handleAreaChange"/>
        </el-form-item>
        <el-form-item :label="$t('iot.projectAddress')" prop="projectAddress">
          <el-input v-model="form.projectAddress" :placeholder="$t('common.enterProjectAddress')" />
        </el-form-item>
        <el-form-item :label="$t('iot.approvalTime')" prop="approvaltime">
          <el-date-picker v-model="form.approvaltime" type="datetime" :placeholder="$t('iot.selectApprovalTime')" :default-value="new Date()"/>
        </el-form-item>
        <el-form-item :label="$t('common.remark')" prop="remark">
          <el-input v-model="form.remark" :placeholder="$t('common.enterRemark')" />
        </el-form-item>
        <el-form-item :label="$t('common.status')" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="normal" class="normal-radio">{{ $t('common.normal') }}</el-radio>
            <el-radio label="hidden" class="hidden-radio">{{ $t('common.hidden') }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t('common.confirm') }}</el-button><el-button @click="cancel">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {listProject,getProject,delProject,addProject,updateProject,listNicknames,Adminlist} from '@/api/iot/faproject'
import {listDistricts, listCities, listProvinces } from '@/api/iot/faArea'
import { options } from 'runjs'
import Template from '@/views/iot/template/index.vue'
import { listUser } from '@/api/iot/tool'
import { provinceList } from '@/utils/address'
export default {
  name: "project",
  components: { Template },
  data() {
    return {
      selectedArea: [], // 选中地区的值
      areaOptions: [], // 省市区数据
      cascaderProps: {
        value: 'id',
        label: 'name',
        children: 'children',
        checkStrictly: true
      },
      isAreasLoaded: false,
      isVisible: true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目表格数据
      projectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        adminId: null,
        projectname: null,
        city: '',
        citycode: '',
        projectAddress: null,
        approvaltime: null,
        lat: null,
        lng: null,
        refreshtime: null,
        createtime: null,
        updatetime: null,
        deletetime: null,
        weigh: null,
        switch: null,
        status: null,
        state: null,
        userId: '',
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getList();
    this.fetchNicknames();
    this.loadProvinces();
    this.fetchUsers();
  },
  methods: {
    options,
    formatDate(timestamp) {
      const date = new Date(timestamp * 1000); // 将秒转换为毫秒
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 获取用户列表数据
    fetchUsers() {
      listUser().then(response => {
        if (response && response.rows) {
          this.options = response.rows.map(user => ({
            userId: user.userId,
            nickName: user.nickName
          }));
          console.log("fetchUsers", this.options);
        }
      }).catch(error => {
        console.error('error', error);
      });
    },
    async fetchNicknames() {
      try {
        const response = await listUser({});
        console.log("5555",response);  // 确保数据格式正确
        if (response && response.rows && Array.isArray(response.rows)) {
          this.options = response.rows.map(item => ({
            userId: item.userId,
            nickName: item.nickName
          }));
        } else {
          console.error('fetchNicknames-error');
        }
      } catch (error) {
        console.error('error:', error);
      }
    },
    // 加载省级数据
    loadProvinces() {
      listProvinces().then(response => {
        console.log("response",response);
        if (response && response.rows && Array.isArray(response.rows)) {
          this.areaOptions=response.rows.filter(province=>province.level===1).map(province=>({
              id: province.id,
              name: province.name,
              level: province.level,
              children: [], // 初始化 children 数组，用于后续加载城市数据
          }));
          this.isAreasLoaded = true;
        }
      });
    },
    handleAreaChange(value) {
      if (!this.isAreasLoaded) return;
      const [selectedProvinceId, selectedCityId, selectedDistrictId] = value;
      // 查找选中的省市区对象
      let selectedProvince = null;
      let selectedCity = null;
      let selectedDistrict = null;
      // 遍历areaOptions找到对应的省市区对象
      this.areaOptions.forEach(province => {
        if (province.id === selectedProvinceId) {
          selectedProvince = province;
          if (selectedCityId) {
            province.children.forEach(city => {
              if (city.id === selectedCityId) {
                selectedCity = city;
                if (selectedDistrictId) {
                  city.children.forEach(district => {
                    if (district.id === selectedDistrictId) {
                      selectedDistrict = district;
                    }
                  });
                }
              }
            });
          }
        }
      });
      // 根据选中的省市区对象设置表单的city字段
      if (selectedProvince && selectedCity && selectedDistrict) {
        this.form.city = `${selectedProvince.name}/${selectedCity.name}/${selectedDistrict.name}`;
        this.form.citycode = selectedDistrict.xzcode;
      } else if (selectedProvince && selectedCity) {
        this.form.city = `${selectedProvince.name}/${selectedCity.name}`;
        this.form.citycode = selectedCity.xzcode;
      } else if (selectedProvince) {
        this.form.city = selectedProvince.name;
      }
      // 如果选择了区县，则关闭下拉框
      if (selectedDistrictId) {
        this.$refs.cascader.toggleDropDownVisible(false);
        console.log("city:",this.form.city);
        console.log("citycode:",this.form.citycode);
      } else if (selectedCityId && !selectedDistrictId) {
        // 市级选择后加载区县
        this.loadDistricts(selectedCityId);
        console.log("city:",this.form.city);
        console.log("citycode:",this.form.citycode);
      } else if (selectedProvinceId && !selectedCityId) {
        // 省级选择后加载城市
        this.loadCities(selectedProvinceId);
        console.log("city:",this.form.city);
        console.log("citycode:",this.form.citycode);
      }
    },
    loadCities(provinceId) {
      listCities(provinceId).then(response => {
        console.log("response",response);
        if (response && Array.isArray(response.rows)) {
          const cities = response.rows;
          const province = this.areaOptions.find(p => p.id === provinceId);
          if (province) {
            province.children = cities.map(city => ({
              id: city.id,
              name: city.name,
              xzcode: city.xzcode,
              level: 2,
              children: [],
            }));
          }
        }
      })
    },
    loadDistricts(cityId) {
      listDistricts(cityId).then(response => {
        console.log("response",response);
        if (response && Array.isArray(response.rows)) {
          const districts = response.rows;
          const province = this.areaOptions.find(p => p.children.some(c => c.id === cityId));
          if (province) {
            const city = province.children.find(c => c.id === cityId);
            if (city) {
              city.children = districts.map(district => ({
                id: district.id,
                name: district.name,
                xzcode: district.xzcode,
                level: 3,
              }));
            }
          }
        }
      })
    },
    /** 查询项目列表 */
    getList() {
      this.loading = true;
      listProject(this.queryParams)
        .then(response => {
          // 格式化列表中的每个项目的时间
          this.projectList = response.rows.map(item => {
            //console.log("101010",response)
            // 将时间戳转换为可读日期格式
            if (item.approvaltime) {
              item.approvaltimeFormatted = this.formatDate(item.approvaltime * 1000); // 转换为毫秒
            }
            // 如果更新时间为null或0，则显示'未更新'
            if (item.updatetime) {
              item.updatetimeFormatted = this.formatDate(item.updatetime); // 转换为毫秒
            } else {
              item.updatetimeFormatted = this.$t('iot.notUpdated');
            }
            return item;
          });
          this.total = response.total;
          this.loading = false;
        })
        .catch(error => {
          console.error('error:', error);
          this.loading = false;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: '',
        id: null,
        adminId: null,
        projectname: null,
        city: '',
        citycode: '',
        projectAddress: null,
        approvaltime: '',
        lat: null,
        lng: null,
        remark: null,
        refreshtime: null,
        createtime: null,
        updatetime:'',
        deletetime: null,
        weigh: null,
        switch: 0,
        status: "normal",
        state: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();  // 清空表单数据
      this.open = true;
      this.title = this.$t('iot.addProject');
      this.selectedArea = [];
      // 获取用户列表数据
      this.fetchNicknames();  // 异步加载用户数据
      // 获取选中的 userId 和 nickName
      const selectedOption = this.options.find(option => option.userId === this.form.userId);
      if (selectedOption) {
        this.form.nickName = selectedOption.nickName;  // 显示对应的 nickName
        this.form.adminId = selectedOption.userId;    // 把 userId 存入 adminId 字段
      }
    },
    // 处理下拉框选择变化
    handleSelectChange(selectedId) {
      const selectedOption = this.options.find(option => option.userId === selectedId);
      if (selectedOption) {
        console.log(`Selected ID: ${selectedId}, nickName: ${selectedOption.nickName}`);
        this.form.nickName = selectedOption.nickName;  // 显示选择的用户昵称
        this.form.adminId = selectedOption.userId;    // 将选择的 userId 存入 adminId 字段
      }
    },
    async handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      const response = await getProject(id);
      console.log("11111", response);
      if (response.code === 200) {
        this.form = response.data;
        this.form.status = response.data.status;
        this.form.approvaltime = this.formatDate(response.data.approvaltime);
        this.form.nickName = response.data.sysUser.nickName;
        this.form.city = response.data.city;
        this.form.userId = response.data.adminId;
        this.open = true;
        this.title = this.$t('iot.editProject');
        this.fetchNicknames();
        if (this.form.city) {
          const cityParts = this.form.city.split('/');
          let selectedProvince = this.areaOptions.find(p => p.name === cityParts[0]);
          if (selectedProvince) {
            console.log('Province found:', selectedProvince);
            await this.loadCities(selectedProvince.id); // 确保市的数据被加载
            console.log('Cities loaded:', selectedProvince.children);
            let selectedCity = selectedProvince.children.find(c => c.name === cityParts[1]);
            if (selectedCity) {
              console.log('City found:', selectedCity);
              await this.loadDistricts(selectedCity.id); // 确保区的数据被加载
              console.log('Districts loaded:', selectedCity.children);
              let selectedDistrict = selectedCity.children.find(d => d.name === cityParts[2]);
              if (selectedDistrict) {
                this.selectedArea = [selectedProvince.id, selectedCity.id, selectedDistrict.id];
              } else {
                this.selectedArea = [selectedProvince.id, selectedCity.id]; // 如果没有找到区，确保只有省和市
              }
            } else {
              this.selectedArea = [selectedProvince.id]; // 如果没有找到市，只有省
            }
          }
        }
      }
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const now = new Date();
          const currentTimeStamp = Math.floor(now.getTime() / 1000);
          this.form.approvaltime = currentTimeStamp; // 设置 approvaltime 为当前时间戳
          // 确保 adminId 已经被设置
          if (!this.form.adminId) {
            console.error("adminId");
            return;
          }
          if (this.form.id) {
            // 更新操作
            this.form.updatetime = currentTimeStamp; // 设置 updatetime 为当前时间戳
            updateProject(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('common.operationSuccess'));
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error("error", error);
              this.$modal.msgError(this.$t('common.operationFailed'));
            });
          } else {
            // 添加操作
            addProject(this.form).then(response => {
              console.log("response：", response);
              this.$modal.msgSuccess(this.$t('common.operationSuccess'));
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error("error", error);
              this.$modal.msgError(this.$t('common.operationFailed'));
            });
          }
        }
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        this.$t('common.confirmDelete') + ' "' + ids + '" ' + this.$t('common.dataItem') + '？',
        this.$t('navbar.tip'),
        {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }
      ).then(() => {
        return delProject(ids);
      }).then(() => {
        this.getList();
        this.$message({
          type: 'success',
          message: this.$t('common.deleteSuccess')
        });
      }).catch(() => {});
    },
  }
};
</script>
<style scoped>
.normal-radio .el-radio__label {
  color: #409EFF; /* 默认颜色，正常状态 */
}
.hidden-radio .el-radio__label {
  color: #BFBFBF; /* 灰色，隐藏状态 */
}
</style>
